
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  poolint.pull.tablename;

import java.sql.ResultSet;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import dbmanager.DBManager;


import pool.bean.Master_table_Bean;
import pool.bean.Property_details_Bean;
import query.query.ParseQuery;

public class Master_table extends IntegrateSubPool
{
	private String tableObject;
	private String poolTablename="master_table";
	private String reflectSchemaProperty = "property_details";
	
 	public Master_table() {
		// TODO Auto-generated constructor stub
	}
	
	public boolean insert(Hashtable<Object,Object> productHash,Hashtable<Object,Object> moduleHash)
	{	
		Vector<Object> propertyVector= new Vector<Object>();
		productTableHash.putAll(productHash);
		ModuleHash.putAll(moduleHash);
	
		propertyVector.addAll(getPropertyVector());		
		System.out.println(" Vector : " + propertyVector);
		
		/** It will insert into M & PL of the POOLDB. **/
		request=poolTablename;
		
		Enumeration< Object > keyEnum = columnNameValue.keys();
		//String condition = new String();
		String master = tableName + "_";  
		while( keyEnum.hasMoreElements())
		{
			String colName = keyEnum.nextElement().toString();
			String colValue = columnNameValue.get( colName ).toString();
			master += colName + "_" + colValue; 
		}
		
		/** Before insert, it will check whether master name is already present or not into the database. **/
		
		@SuppressWarnings("unused")
		String tempStr; // If object not found in Master than it will get error, and it will insert into database.
		try
		{
			tempStr = getMaster( columnNameValue );
			return true;
		}
		catch (Exception e) 
		{
			try 
			{
				/**Setting request parameters like process, user name, password, etc.*/
				setRequestParameter();
				
				/** Inserting Master & Property...**/
				System.out.println(" Integration::Operation::performOperation::Add:: Insert Process... ");
				Master_table_Bean mtb = new Master_table_Bean();
				mtb.setReqParam(req);
				mtb.setNewMasterObject(master);
				mtb.setPropertyVector(propertyVector);
				System.out.println(" Integration::Operation::performOperation::Add::\n " + mtb.insert());
				return true;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return false;
		}
	}	
	
	
	public Vector<Object> getPropertyVector()
	{
		Vector<Object> propertyVect = new Vector<Object>();
		boolean FLAG = false;		
	//	Enumeration<Object> poolIte = productTableHash.keys();
		Enumeration<Object> poolIte = ModuleHash.keys();
		while(poolIte.hasMoreElements())
		{
			try 
			{
				String key = poolIte.nextElement().toString();
				String field = ModuleHash.get(key).toString();
				String value = productTableHash.get(key).toString();
				//key = ModuleHash.get(key).toString();
				
				Hashtable<Object, Object> hash = new Hashtable<Object, Object>();
				hash.put("pid", field);
				hash.put("pv", value);
				propertyVect.add(hash);
				FLAG = true;
			} catch (Exception e) { }
		}
		if(FLAG)
		{
			String tableFieldId = gin.getId(tableField);
			String tableNameId = gin.getId(tableName);
			String query="select mid from property_details where pid="+tableFieldId+" and pv="+tableNameId+"";
			ResultSet rs = DBManager.getSelect(query);			
			try {
				rs.next();
				tableObject=rs.getString(1);	
				rs.close();
			} catch (Exception e) { }
			Hashtable< Object, Object > hash = new Hashtable< Object, Object >();
			hash.put("pid", "type");
			hash.put("pv", gin.getItem(tableObject));
			propertyVect.add(hash);
		}
		return propertyVect;
	}
	
	/*private String getMaster(String columnNameValue) throws Exception
	{
		String tableValue;
		String tablenameId = gin.getId("tablename");
		String tableId = gin.getId(tableName);
		String query1= "select mid from "+reflectSchemaProperty+" where pid="+tablenameId+" and pv="+tableId;
		ResultSet temp = dbsql.getSelect(query1);
		temp.next();
		tableValue= temp.getString("mid");
		//tableValue = tableObject;
		String value = gin.getId(columnNameValue);
		String query = "SELECT p.mid FROM " + reflectSchemaProperty + " p JOIN " + reflectSchemaProperty + " p1 ";
		query = query + "ON (p.mid = p1.mid) WHERE p.pid = " + gin.getId("TYPE") + " AND p.pv = " + tableValue + " AND p1.pid = " + gin.getId(columnName) + " AND p.td is null AND ";
		if(!value.equals("0"))
		{				
			query = query + " p1.pv = " + value;
		}
		else
		{
			query = query + " p1.vt = '" + columnNameValue + "'";
		}
		temp = dbsql.getSelect(query);
		temp.next();
		return temp.getString("mid");
	}*/
	
	
	private String getMaster( Hashtable< Object , Object > condition ) throws Exception
	{
		ParseQuery query = new ParseQuery();
		query.SetCondition(condition);
		query.SetTableName("master_table");
		Hashtable<Object, Object> fieldHash = new Hashtable<Object, Object>();
		fieldHash.put("field", "mastername");		
		query.SetFieldList(fieldHash);
		query.processQuery();
		String[] id = query.getbuffer();
		String mid = id[1];
		return mid;
	}
	
	
	public boolean update(Hashtable<Object,Object> productHash,Hashtable<Object,Object> moduleHash)
	{

		Vector<Object> propertyVector= new Vector<Object>();
		productTableHash.putAll(productHash);
		ModuleHash.putAll(moduleHash);
		
		propertyVector.addAll(getPropertyVector());		
		System.out.println(" Vector : " + propertyVector);
		
		/** It will insert into M & PL of the POOLDB. **/
		request = reflectSchemaProperty;
		//String master = tableName + "_" + oldcolumnNameValue;		
		
		/** Before Update, it will check whether master name is already present or not into the database. **/
		
		String tempStr = ""; // If object not found in Master than it will get error, and it will insert into database.
		try
		{
			tempStr = getMaster( oldColumnNameValue );
			//String mid = gin.getItem(tempStr);
			String mid = tempStr;
			System.out.println(" Integration::Operation::performOperation::Mod:: Update process....");
			Hashtable<Object, Object> tempVec = new Hashtable<Object, Object>();
			//tempVec.put("mid", gin.getItem(tempStr));
			
			//String fieldValue = getFieldName();		
			
			//tempVec.put("pid", fieldValue);
			
			/*Enumeration< Object > valEnum = oldColumnNameValue.elements();
			while( valEnum.hasMoreElements() )
			{
				String fieldValue = getFieldName();
				tempVec.put("pid", fieldValue);
				tempVec.put("pv", valEnum.nextElement() );
			}*/
			//tempVec.put("pv", oldcolumnNameValue);
			
			Hashtable<Object, Object> colName = new Hashtable<Object, Object>();
			colName = getFieldName(); // call to getFiledName(), which converts the column name into fieldname. 
			
			Hashtable<Object, Object> temp = new Hashtable<Object, Object>();
			temp.putAll(oldColumnNameValue);
			
			// generates field & value hash.
			Enumeration<Object> keys = colName.keys();
			while(keys.hasMoreElements())
			{
				String key = keys.nextElement().toString();
				if(temp.containsKey(key))
				{
					String value = temp.get(key).toString();
					temp.remove(key);
					temp.put(key, value);
				}				
			}
			keys = null;
			
			// converts into the POOL format.
			keys = temp.keys();
			while(keys.hasMoreElements())
			{
				String key = keys.nextElement().toString();
				Hashtable<Object, Object> temp1 = new Hashtable<Object, Object>();
				temp1.put("mid", mid);
				temp1.put("pid", key);
				temp1.put("pv", temp.get(key).toString());
				tempVec.putAll(temp1);	
			}
			
			Vector< Object > oldVector = new Vector< Object > (); 
			oldVector.add(tempVec);
			
			/**Setting request parameters like process, user name, password, etc.*/
			setRequestParameter();
			
			/**Updating property in Property_details.*/
			Property_details_Bean pdb = new Property_details_Bean();
			pdb.setReqParam(req);
			pdb.setOldPropertyVector(oldVector);
			pdb.setNewPropertyVector(propertyVector);

			/** It will update record into database.*/
			System.out.println(" Integration::Operation::performOperation:: Update Message : " + pdb.update());
			return true;
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			System.out.println(" Integration::Operation::performOperation Property Not Present in the database...");			
		}			
		return false;	
	}
	
	
	public boolean delete(Hashtable<Object,Object> productHash,Hashtable<Object,Object> moduleHash)
	{
		System.out.println(" Integration::Operation::performOperation::Del:: Delete process....");
		
		request = reflectSchemaProperty;
		
		/** Before Delete, it will check whether master name is already present or not into the database. **/
 		
		String tempStr = ""; // If object not found in Master than it will get error, and it will insert into database.
		try
		{
			tempStr = getMaster( oldColumnNameValue );
			
			/**Setting request parameters like process, user name, password, etc.*/
			setRequestParameter();
						
			/** Deleting property from database. */
			String master = gin.getItem(tempStr);
			Master_table_Bean mtb = new Master_table_Bean();
			mtb.setReqParam(req);
			mtb.setNewMasterObject(master);		
			
			/** It will Delete record from the database.*/
			System.out.println(" Integration::Operation::performOperation:: Delete Message : " + mtb.delete());
			return true;
		}
		catch (Exception e) 
		{
			System.out.println(" Integration::Operation::performOperation Property Not Present in the database...");			
		}			
		return false;	
	}

	
	/*public boolean isParentAvailable()
	{		
		boolean flag=false;
		
		ResultSet rs = getJoinResultSet();
		try 
		{
			rs.next();
			String id=rs.getString(1);	
			flag=false;
		}
		catch (Exception e)
		{
			try 
			{
				String fieldname=gin.getId(getFieldName());
				String  query;
				String value=gin.getId(columnValue);
				if(!value.equals("0"))
				{				
					query="select mid from "+reflectSchemaProperty+" where pid="+fieldname+" and pv="+value;
				}
				else
				{
					query="select mid from "+reflectSchemaProperty+" where pid="+fieldname+" and vt="+columnValue;
				}
				
				rs= dbsql.getSelect(query);
				rs.next();
				String id=rs.getString(1);
				flag= true;
			} 
			catch (Exception e1)
			{
				flag= false;
			}					
		}
		return flag;
	}*/
	
	
	public boolean isParentAvailable()
	{		
		boolean flag=false;
		
		ResultSet rs = getJoinResultSet();
		try 
		{
			rs.next();
			String id=rs.getString(1);	
			flag=false;
			rs.close();
		}
		catch (Exception e)
		{
			try 
			{
				ParseQuery query = new ParseQuery();
				query.SetCondition(columnNameValue);
				query.SetTableName("master_table");
				Hashtable<Object, Object> fieldHash = new Hashtable<Object, Object>();
				fieldHash.put("field", "mastername");		
				query.SetFieldList(fieldHash);
				query.processQuery();
				String[] id = query.getbuffer();
				if(id.length > 1)
					return flag= true;		
				/*String  query;
				String condition = new String();
				Enumeration< Object > enumEle = columnNameValue.elements();
				
				while( enumEle.hasMoreElements() )
				{
					String fieldname = gin.getId(getFieldName());
					String colName = enumEle.nextElement().toString(); 
					String value = gin.getId(colName);
					//chrome://ubufox/content/startpage.html
					if(!value.equals("0"))
					{				
						condition += "pid = " + fieldname + "and pv = " + value;
						//query="select mid from "+reflectSchemaProperty+" where pid="+fieldname+" and pv="+value;
					}
					else
					{
						condition += "pid = " + fieldname + "and vt = " + value;
						//query="select mid from "+reflectSchemaProperty+" where pid="+fieldname+" and vt="+columnValue;
					}
				}
				
				query = "select mid from " + reflectSchemaProperty + " where " + condition;   
				rs= DBManager.getSelect(query);
				rs.next();
				String id = rs.getString(1);
				rs.close();*/
			} 
			catch (Exception e1)
			{
				flag= false;
			}					
		}
		return flag;
	}
}
